package com.yu8home.opcua.test;

import com.yu8home.opcua.OpcUAUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription;
import org.eclipse.milo.opcua.stack.core.AttributeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
import org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode;
import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
import org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest;
import org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters;
import org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId;

import static com.google.common.collect.Lists.newArrayList;
import static org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint;

@Slf4j
public class SingleSub0 {

    public static void main(String[] args) throws Exception {
        OpcUAUtil.getConnect();
        createSubscribe();
        System.in.read();
    }

    public static void createSubscribe() throws Exception {
        UaSubscription subscription = OpcUAUtil.opcUaClient.getSubscriptionManager().createSubscription(1000.0).get();

        String node = "Simulation Examples.Functions.m";
        NodeId nodeId = new NodeId(OpcUAUtil.namespaceIndex, node);

        ReadValueId readValueId = new ReadValueId(
                nodeId,
                AttributeId.Value.uid(),
                null,
                QualifiedName.NULL_VALUE
        );

        MonitoringParameters parameters = new MonitoringParameters(
                subscription.nextClientHandle(),
                1000.0,      // sampling interval
                null,                      // filter, null means use default
                uint(10),            // queue size
                true                       // discard oldest
        );

        MonitoredItemCreateRequest request = new MonitoredItemCreateRequest(
                readValueId,
                MonitoringMode.Reporting,
                parameters
        );

        subscription.createMonitoredItems(
                TimestampsToReturn.Both,
                newArrayList(request),
                (item, id) ->
                        item.setValueConsumer((k, v) -> {
                            NodeId _nodeId = k.getReadValueId().getNodeId();
                            log.info("订阅：{} = {}", _nodeId.getIdentifier(), v.getValue().getValue());
                        })
        ).get();
    }

}
